package xhwl.hmo.mall.ui;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import de.greenrobot.event.EventBus;
import rx.functions.Action1;
import xhwl.hmo.mall.BaseActivity;
import xhwl.hmo.mall.Constant;
import xhwl.hmo.mall.IntentConstants;
import xhwl.hmo.mall.R;
import xhwl.hmo.mall.bean.CommentPicInfo;
import xhwl.hmo.mall.bean.ImageItem;
import xhwl.hmo.mall.event.OrderStateChangeEvent;
import xhwl.hmo.mall.event.ImageEvent;
import xhwl.hmo.mall.http.api.AddCommentApi;
import xhwl.hmo.mall.http.api.UploadPicApi;
import xhwl.hmo.mall.http.bean.resp.HttpResp;
import xhwl.hmo.mall.http.bean.resp.ReferralPicBean;
import xhwl.hmo.mall.utils.BitmapUtil;
import xhwl.hmo.mall.utils.SpUtil;
import xhwl.hmo.mall.utils.StringUtil;
import xhwl.hmo.mall.utils.ToastUtil;
import xhwl.hmo.mall.utils.XHLog;
import xhwl.hmo.mall.views.MyDialog;
import xhwl.hmo.mall.views.PopSelectPic;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;

/**
 * Created by admin on 2017-10-26.
 */

public class AddCommentActivity extends BaseActivity implements View.OnClickListener, PopSelectPic.PopSelectBtnClickListener {
    private static final int REQUEST_CODE_VIEW_PIC = 0x000001;
    private static final int TAKE_PICTURE = 0x000000;
    public static final String EXTRA_GOOD_ID = "goodId";
    public static final String EXTRA_BUY_ID = "buyId";
    private static final int MAX_IMAGE_SIZE = 6;
    private static final String COMMENT = "最多可上传6张图片";
    private LinearLayout llCommentMain;
    private TextView tvScroe;
    private RatingBar ratingBar;
    private EditText etComment;
    private GridView myGridView;
    private Button btnSubmit;
    private TextView mRemind;//图片张数提示
    List<CommentPicInfo> picInfos = new ArrayList<>();
    GridImageAdapter adapter;
    private String path = "";
    int score;
    String buyId, goodId;
    MyDialog myDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        goodId = getIntent().getStringExtra(EXTRA_GOOD_ID);
        buyId = getIntent().getStringExtra(EXTRA_BUY_ID);
        setContentView(R.layout.activity_add_comment);

    }

    @Override
    public void initViews() {
        initTitleViews();
        this.llCommentMain = (LinearLayout) findViewById(R.id.llCommentMain);
        this.btnSubmit = (Button) findViewById(R.id.btnSubmit);
        this.myGridView = (GridView) findViewById(R.id.myGridView);
        this.etComment = (EditText) findViewById(R.id.etComment);
        this.ratingBar = (RatingBar) findViewById(R.id.ratingBar);
        this.tvScroe = (TextView) findViewById(R.id.tvScroe);
        this.mRemind = (TextView) findViewById(R.id.tvRemind);
        this.mRemind.setText(COMMENT);
        //设置RatingBar5颗星
        ratingBar.setNumStars(5);
        //设置当前的星数
        ratingBar.setRating(0f);
        //设置RatingBar 评分的步长
        ratingBar.setStepSize(0.5f);
    }

    @Override
    protected void setUpTitleView() {
        super.setUpTitleView();
        this.titleTextView.setText("填写评价");
    }

    @Override
    protected void processOper() {
        super.processOper();
        CommentPicInfo info = new CommentPicInfo();
        info.saveUrl = "placeHolder";
        picInfos.add(info);
        adapter = new GridImageAdapter();
        myGridView.setAdapter(adapter);

    }

    @Override
    public void initListener() {
        myGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == picInfos.size() - 1) {
                    PopSelectPic popfront = new PopSelectPic(AddCommentActivity.this, llCommentMain);
                    popfront.setCallBack(AddCommentActivity.this);
                } else {
//                    Intent intent = new Intent(PutQuestionsActivity.this, ImageZoomActivity.class);
//                    intent.putExtra(IntentConstants.EXTRA_IMAGE, mDataList.get(position));
//                    intent.putExtra(IntentConstants.EXTRA_CURRENT_IMG_POSITION, position);
//                    startActivityForResult(intent,REQUEST_CODE_VIEW_PIC);

                }
            }
        });
        ratingBar.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() {
            @Override
            public void onRatingChanged(RatingBar ratingBar, float v, boolean b) {
                score = (int) (v * 2);
            }
        });
        btnSubmit.setOnClickListener(this);
    }

    @Override
    public void loadData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnSubmit:
                if (vilidInput()) {
                    if (shouldConfirmTxt && StringUtil.isEmpty(etComment.getText().toString())) {
                        showConfirmDialog(0);
                    } else {
                        boolean hasFail = false;
                        for (CommentPicInfo picInfo : picInfos) {
                            if (picInfo.status == CommentPicInfo.Status.Fail) {
                                hasFail = true;
                                break;
                            }
                        }
                        if (hasFail) {
                            if (shouldConfirmPic) {
                                showConfirmDialog(1);
                            } else {
                                String urls = getCommentPicUrls();
                                submitComment(urls);
                            }
                        } else {
                            String urls = getCommentPicUrls();
                            submitComment(urls);
                        }
                    }

                }
                break;
        }
    }

    boolean shouldConfirmTxt = true;//是否需要确认文本为空
    boolean shouldConfirmPic = true;

    /*
      type 0:文字评论为空 1：有上传失败的图片
     */
    private void showConfirmDialog(final int type) {

        View view = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_comment_confirm, null);
        TextView tvCancle = (TextView) view.findViewById(R.id.tvCancle);
        TextView tvConfirm = (TextView) view.findViewById(R.id.tvConfirm);
        final TextView tvMsg = (TextView) view.findViewById(R.id.tvMsg);
        tvMsg.setText(type == 0 ? "尚未填写文字评价信息\n是否确认提交" : "有图片上传未成功\n是否确认提交");
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                myDialog.dismiss();
            }
        });

        tvConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type == 0) {
                    shouldConfirmTxt = false;

                } else {
                    shouldConfirmPic = false;
                }
                myDialog.dismiss();
                btnSubmit.performClick();
            }
        });
        myDialog = new MyDialog(this, view, Gravity.CENTER);
        myDialog.setCanceledOnTouchOutside(false);
        myDialog.show();

    }

    private void submitComment(String urls) {
        AddCommentApi api = new AddCommentApi(SpUtil.getString(SpUtil.MEMBER_MOBILE, ""), buyId, goodId, score + "", etComment.getText().toString(),
                urls);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<HttpResp>() {
            @Override
            public void onNext(HttpResp resp) {
                if (resp.isOk()) {
                    ToastUtil.showToast(mContext, "添加评论成功");
                    EventBus.getDefault().post(new OrderStateChangeEvent());
                    setResult(RESULT_OK);
                    finish();
                } else {
                    ToastUtil.showToast(mContext, resp.message);
                }
            }
        });
    }


    private String getCommentPicUrls() {
        String urls = "";
        for (CommentPicInfo picInfo : picInfos) {
            if (picInfo.status != CommentPicInfo.Status.Success) {
                //有失败或上传中的图片
                break;
            } else {
                urls += picInfo.url + ";";
            }
        }
        return urls;
    }

    private boolean vilidInput() {
        String msg = "";
        if (score == 0) {
            msg = "请评价星级";
        }
        if (!StringUtil.isEmpty(msg)) {
            ToastUtil.showToast(mContext, msg);
            return false;
        }
        return true;
    }

    int base = 10;

    private void uploadPic(final int pos, final File file) {
        if (file == null)
            return;
        final UploadPicApi api = new UploadPicApi(mContext, new File[]{file});
        api.setCallback(new UploadPicApi.Callback() {
            @Override
            public void onProcess(int id, final int percent) {
                Log.e("tag11", "1 id=" + id + "  " + percent + "%");
                picInfos.get(pos).percent = percent;
                if (percent % base == 1) {
                    base += 10;
                    adapter.notifyDataSetChanged();
                }
            }
        });
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<ArrayList<ReferralPicBean>>() {
            @Override
            public void onStart() {
                super.onStart();
                picInfos.get(pos).percent = 0;
                picInfos.get(pos).url = "";
                picInfos.get(pos).status = CommentPicInfo.Status.Uploading;
                XHLog.e(pos + "开始上传..");
                adapter.notifyDataSetChanged();
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onNext(final ArrayList<ReferralPicBean> picBeanList) {
                picInfos.get(pos).url = picBeanList.get(0).getUrl_big();
                picInfos.get(pos).status = CommentPicInfo.Status.Success;
                adapter.notifyDataSetChanged();
                handler.sendEmptyMessage(0);
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
                picInfos.get(pos).percent = 0;
                picInfos.get(pos).url = "";
                picInfos.get(pos).status = CommentPicInfo.Status.Fail;
                adapter.notifyDataSetChanged();
                handler.sendEmptyMessage(0);


            }
        });
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            boolean isUploading = false;
            for (CommentPicInfo picInfo : picInfos) {
                if (picInfo.status == CommentPicInfo.Status.Uploading) {
                    isUploading = true;
                    break;
                }
            }
            if (!isUploading) {//全部上传完成、成功或失败
                enableSubmitBtn(true);
            } else {
                enableSubmitBtn(false);
            }
        }
    };

    private void enableSubmitBtn(boolean enable) {
        if (enable) {
            btnSubmit.setEnabled(enable);
            btnSubmit.setBackgroundResource(R.drawable.shape_btn_bg);
        } else {
            btnSubmit.setEnabled(enable);
            btnSubmit.setBackgroundResource(R.drawable.shape_btn_disable_bg);
        }
    }

    //图片处理开始
    private int getAvailableSize() {
        int availSize = MAX_IMAGE_SIZE - picInfos.size() + 1;
        if (availSize >= 0) {
            return availSize;
        }
        return 0;
    }

    @Override
    public void onTakePhotoClick() {
        takePhoto();
    }

    @Override
    public void onSelectPicClick() {
        pickPicture();
    }

    private void pickPicture() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            Intent intent = new Intent(mContext, ImageBucketChooseActivity.class);
                            intent.putExtra(IntentConstants.EXTRA_CAN_ADD_IMAGE_SIZE, getAvailableSize());
                            startActivity(intent);
                        } else {
                            ToastUtil.showToast(mContext, "请打开提示对应权限,否则功能无法使用");
                        }
                    }

                });

    }


    public void takePhoto() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean granted) {
                        if (granted) {
                            Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                            File vFile = new File(Constant.SAVE_PIC_PATH, String.valueOf(System.currentTimeMillis()) + ".jpg");
                            if (!vFile.exists()) {
                                File vDirPath = vFile.getParentFile();
                                vDirPath.mkdirs();
                            } else {
                                if (vFile.exists()) {
                                    vFile.delete();
                                }
                            }
                            path = vFile.getPath();
                            Uri cameraUri;
                            if (Build.VERSION.SDK_INT >= 24) {
                                cameraUri = FileProvider.getUriForFile(mContext, "xhwl.hmo.mall.fileProvider", vFile);
                            } else {
                                cameraUri = Uri.fromFile(vFile);
                            }
                            openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
                            startActivityForResult(openCameraIntent, TAKE_PICTURE);
                        } else {
                            ToastUtil.showToast(mContext, "请打开提示对应权限,否则功能无法使用");
                        }
                    }

                });

    }

    public void onEvent(ImageEvent event) {
        if (event == null)
            return;

        Collection<ImageItem> collection = event.getCollection();

        for (ImageItem item : collection) {// 目前只能选择一张图片，可上传多张图片时，需根据接口定义修改s
            XHLog.e("sourcePath=" + item.getSourcePath());
            initImageFiles(item);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == TAKE_PICTURE) {
                ImageItem item = new ImageItem();
                item.sourcePath = path;
                XHLog.e("sourcePath=" + item.sourcePath);
                initImageFiles(item);
            }
        }

    }

    private void initImageFiles(ImageItem item) {
        String fileName = BitmapUtil.handleImage(mContext, item.sourcePath, 200);
        int pos = picInfos.size() - 1;
        CommentPicInfo picInfo = new CommentPicInfo();
        picInfo.saveUrl = fileName;
        picInfos.add(pos, picInfo);
        notifyDataChanged();
        uploadPic(pos, new File(fileName));

    }

    //图片处理结束
    private void notifyDataChanged() {
        if (picInfos.size() > 0) {
            mRemind.setVisibility(View.GONE);
        } else {
            mRemind.setVisibility(View.VISIBLE);
        }
        if (picInfos.size() == MAX_IMAGE_SIZE + 1) {//最大值是隐藏选择图片imageview
            picInfos.remove(MAX_IMAGE_SIZE);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myDialog != null && myDialog.isShowing()) {
            myDialog.dismiss();
        }
        EventBus.getDefault().unregister(this);
    }

    public class GridImageAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return picInfos.size();
        }

        @Override
        public Object getItem(int i) {
            return picInfos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup viewGroup) {
            CommentPicInfo picInfo = picInfos.get(position);
            convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_image, null);
            ImageView ivPic = (ImageView) convertView.findViewById(R.id.item_grid_image);
            ImageView ivDel = (ImageView) convertView.findViewById(R.id.iv_delet_icon);
            final View viewBg = convertView.findViewById(R.id.item_grid_view);
            final TextView tvPercent = (TextView) convertView.findViewById(R.id.item_grid_percent);
            if ("placeHolder".equals(picInfos.get(position).saveUrl)) {
                ivDel.setVisibility(View.INVISIBLE);
                tvPercent.setVisibility(View.GONE);
                viewBg.setVisibility(View.GONE);
                ivPic.setImageResource(R.drawable.pick_pic);
            } else {
                if (picInfo.status == CommentPicInfo.Status.Fail) {
                    viewBg.setVisibility(View.VISIBLE);
                    viewBg.setAlpha(0.7f);
                    tvPercent.setVisibility(View.VISIBLE);
                    tvPercent.setText("重新上传");
                    tvPercent.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            uploadPic(position, new File(picInfos.get(position).saveUrl));
                        }
                    });
                } else if (picInfo.status == CommentPicInfo.Status.Success) {
                    viewBg.setVisibility(View.GONE);
                    tvPercent.setVisibility(View.GONE);
                } else {
                    viewBg.setVisibility(View.VISIBLE);
                    tvPercent.setVisibility(View.VISIBLE);
                    tvPercent.setText(picInfo.percent + "%");
                    int count = picInfo.percent % 10;
                    float sum = count * 0.07f;
                    viewBg.setAlpha(0.7f - sum);
                }
                ivDel.setVisibility(View.VISIBLE);
                Glide.with(mContext)//加载本地图片
                        .load(picInfos.get(position).saveUrl)
//                        .diskCacheStrategy(DiskCacheStrategy.NONE)
//                        .skipMemoryCache(true)
//                        .error(R.drawable.pic_add)
                        .into(ivPic);
                ivDel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                        picInfos.remove(position);
                        boolean isContain = false;
                        for (CommentPicInfo picInfo : picInfos) {
                            if (picInfo.saveUrl.equals("placeHolder")) {
                                isContain = true;
                            }
                        }
                        if (!isContain) {
                            CommentPicInfo picInfo = new CommentPicInfo();
                            picInfo.saveUrl = "placeHolder";
                            picInfos.add(picInfo);
                        }

                        notifyDataSetChanged();
                    }
                });

            }
            return convertView;
        }
    }
}
